using System;
using Microsoft.SharePoint;

namespace Sapphire.Linq.Test
{
    public static class TestGenerator
    {
        public static void EnsureTestData(SPWeb web)
        {
            var tasksList = EnsureList(web, "Tasks", SPListTemplateType.Tasks);
            var customList = EnsureList(web, "Custom1", SPListTemplateType.GenericList);

            EnsureLookupField(web, customList, tasksList);

            if (tasksList.ItemCount == 0)
                GenerateItems(tasksList);

            if (customList.ItemCount == 0)
                GenerateItems(customList);
        }

        private static void GenerateItems(SPList list)
        {
            for (int i = 0; i < 100; i++)
            {
                var newItem = list.Items.Add();
                newItem["Title"] = string.Format("New {0} {1}", list.Title, i);
                newItem.Update();
            }
        }

        private static void EnsureLookupField(SPWeb web, SPList hostList, SPList targetList)
        {
            if (hostList.Fields.ContainsField(targetList.Title))
                return;

            var fieldName = hostList.Fields.AddLookup(targetList.Title, targetList.ID, false);
            var field = hostList.Fields[fieldName] as SPFieldLookup;
            field.AllowMultipleValues = true;
            field.Update(true);
        }

        private static SPList EnsureList(SPWeb web, string title, SPListTemplateType type)
        {
            if (ContainsList(web, title))
                return web.Lists[title];

            return web.Lists[web.Lists.Add(title, string.Empty, type)];
        }

        private static bool ContainsList(SPWeb web, string name)
        {
            try
            {
                return web.Lists[name] != null;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}